import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'ServiceLocator.dart';
import 'TelAndSmsService.dart';
import 'request.dart' as res;

//import 'dataBaseOpera.dart' as dat;
import 'fileSave.dart' as fil;

// import 'package:amap_base/amap_base.dart';
import 'dart:async';
import 'mainListDetail.dart' as detail;
import 'map.dart' as map;
import 'package:permission_handler/permission_handler.dart';

class listState extends StatefulWidget {
  @override
  _listStateState createState() => _listStateState();
}

class _listStateState extends State<listState>
    with SingleTickerProviderStateMixin {
  TelAndSmsService _service = locator<TelAndSmsService>(); // 电话服务
  TabController controller; // 先声明变量
  bool isLoading = false;
  ScrollController scrollController = ScrollController(); // 滚动控制器
  int max = 0;
  int max1 = 0;
  int max2 = 0;
  String status = '0';
  String userId = '';
  List<dynamic> list = new List<dynamic>();
  List<dynamic> list1 = new List<dynamic>();
  List<dynamic> list2 = new List<dynamic>();
  int offset = 0;
  int limit = 10;
  int offset1 = 0;
  int limit1 = 10;
  int offset2 = 0;
  int limit2 = 10;
  String btnName = '抢单';

  // 地图定位
  // final _amapLocation = AMapLocation();
  var _result = '';

  //初始化定位监听
//   void _initLocation() async {
//     _amapLocation.init();
//
//     final options = LocationClientOptions(
//       isOnceLocation: false,
//       locatingWithReGeocode: true,
//     );
//
//     if (await Permissions().requestPermission()) {
//       _amapLocation.startLocate(options).listen((_) => setState(() {
//             _result =
//                 '坐标：${_.longitude}，${_.latitude} @ ${DateTime.now().hour}:${DateTime.now().minute}:${DateTime.now().second}';
//             print('坐标：${_.longitude.runtimeType.toString()}，${_.latitude}----' +
//                 userId);
// //        res.addPosition(_.longitude,_.latitude, userId);
//           }));
//     } else {
//       setState(() {
//         _result = "无定位权限";
//       });
//     }
//   }
  getLocation() async {
    print("getLocation===");
    if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
      // Use location.
      final location = await AmapLocation.instance.fetchLocation();
    } else {
      if (await Permission.contacts.request().isGranted) {
        // Either the permission was already granted before or the user just granted it.
        final location = await AmapLocation.instance.fetchLocation();
        print("getLocation===  $location");
      } else {}
    }
  }

  // 数据变更
  alterPage(String sign) async {
    if (sign == null || sign == '') {
      if (this.status == '0') {
        this.offset = this.limit;
        this.limit = this.limit + 10;
        await res.getListData('3', userId, offset, limit).then((value) => {
              this.list = value,
              this.max = value.length,
              this.isLoading = false
            });
      } else if (this.status == '1') {
        this.offset1 = this.limit1;
        this.limit1 = this.limit1 + 10;
        await res.getListData('0', userId, offset1, limit1).then((value) => {
              this.list1 = value,
              this.max1 = value.length,
              this.isLoading = false
            });
      } else if (this.status == '2') {
        this.offset2 = this.limit2;
        this.limit2 = this.limit2 + 10;
        await res.getListData('1', userId, offset2, limit2).then((value) => {
              this.list2 = value,
              this.max2 = value.length,
              this.isLoading = false
            });
      }
    } else {
      if (this.status == '0') {
        this.offset = 0;
        this.limit = 10;
        res.getListData('3', userId, offset, limit).then((value) => {
              setState(() {
                this.list = value;
                this.max = value.length;
                this.isLoading = false;
              })
            });
      } else if (this.status == '1') {
        this.offset1 = 0;
        this.limit1 = 10;
        res.getListData('0', userId, offset1, limit1).then((value) => {
              setState(() {
                this.list1 = value;
                this.max1 = value.length;
                this.isLoading = false;
              })
            });
      } else if (this.status == '2') {
        this.offset2 = 0;
        this.limit2 = 10;
        //更新视图.
        res.getListData('1', userId, offset2, limit2).then((value) => {
              setState(() {
                this.list2 = value;
                this.max2 = value.length;
                this.isLoading = false;
              })
            });
      }
    }
  }

  // 获取用户id
  _getCounter() async {
//    SharedPreferences prefs = await SharedPreferences.getInstance();
//    userId = prefs.getString('userId');
//    await dat.getBook(1).then((value) => {
//        userId = value["userId"]
//    });
//    userId = await dat.getBook(1);
    userId = await fil.readCounter();
    await res.getListData('0', userId, 0, 10).then((value) => {
          setState(() {
            this.list = value;
            this.max = value.length;
            this.isLoading = false;
          })
        });
    await res.getListData('1', userId, 0, 10).then((value) => {
          setState(() {
            this.list1 = value;
            this.max1 = value.length;
            this.isLoading = false;
          })
        });
    await res.getListData('2', userId, 0, 10).then((value) => {
          setState(() {
            this.list2 = value;
            this.max2 = value.length;
            this.isLoading = false;
          })
        });
  }

  // 生成列表项
  Widget buildListData(BuildContext context, dynamic obj) {
    var card = new SizedBox(
//    height: 550.0,  //设置高度
      child: new Card(
        elevation: 15.0, //设置阴影
        margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10.0))), //设置圆角
        child: new Column(
          // card只能有一个widget，但这个widget内容可以包含其他的widget
          children: [
            new ListTile(
              title: Row(
                children: <Widget>[
                  new Container(
                    child: Image.asset('images/time.png'),
                    width: 20,
                    height: 20,
                  ),
                  new Text('30分钟内',
                      style: new TextStyle(
                          color: Color.fromRGBO(255, 0, 42, 1),
                          fontWeight: FontWeight.w100,
                          fontSize: 13)),
                  new Text('送达',
                      style: new TextStyle(
                          color: Color.fromRGBO(0, 0, 0, 1),
                          fontWeight: FontWeight.w100,
                          fontSize: 13))
                ],
              ),
              trailing: Text(obj['freight'].toString() + '元',
                  style: TextStyle(
                      color: Color.fromRGBO(255, 0, 42, 1),
                      fontWeight: FontWeight.bold,
                      fontSize: 16)),
              onTap: () {
                Navigator.push(context, MaterialPageRoute(builder: (_) {
                  String statusName;
                  if (this.status == '0') {
                    statusName = '新订单';
                  } else if (this.status == '1') {
                    statusName = '待取货';
                  } else if (this.status == '2') {
                    statusName = '派送中';
                  }
                  return detail.listState(statusName, this.status,
                      obj['orderId'].toString(), obj['id'].toString(), userId);
                }));
              },
            ),
            new ListTile(
                leading: Text('1.3KM  ',
                    style: new TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Color.fromRGBO(0, 0, 0, 1))),
                title: Row(
                  children: <Widget>[
                    new Expanded(
                      child: new Text(obj['shopName'].toString(),
                          style: new TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: Color.fromRGBO(0, 0, 0, 1))),
                    ),
                    new Expanded(
                      child: new Text(' #' + obj['orderNo'].toString() + '号',
                          style: new TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: Color.fromRGBO(255, 0, 42, 1))),
                    ),
                  ],
                ),
                subtitle: Text(obj['shopAddress'].toString()),
                trailing: IconButton(
                    icon: ImageIcon(AssetImage("images/phone.png")),
                    onPressed: () {
                      _service.call(obj['shopPhone']);
                    })
//                Row(
//                  children: <Widget>[
//                  GestureDetector(
//                    onTap: ()=>{
//                      Navigator.push(context, MaterialPageRoute(builder: (_) {
//                        return map.MapPage();
//                      }))
//                    },
//                    child: Container(
//                      child: Image.asset('images/map.png'),
//                      width: 30,
//                      height: 30,
//                    ),
//                  ),
//                  ],
//                )
                ),
            new ListTile(
                leading: Text('3.3KM  ',
                    style: new TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Color.fromRGBO(0, 0, 0, 1))),
                title: new Text(obj['consignee'].toString(),
                    style: new TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Color.fromRGBO(0, 0, 0, 1))),
                subtitle: Text(obj['address'].toString()),
                trailing: IconButton(
                    icon: ImageIcon(AssetImage("images/phone.png")),
                    onPressed: () {
                      _service.call(obj['contactNumber']);
                    })
//                Row(
//                  children: <Widget>[
//                  GestureDetector(
//                    onTap: ()=>{
//                      print('打开地图')
//                    },
//                    child: Container(
//                      child: Image.asset('images/map.png'),
//                      width: 30,
//                      height: 30,
//                    ),
//                  ),
//                  ],
//                )
                ),
            new ListTile(
                title: Container(
              child: Material(
                  child: Ink(
                decoration: BoxDecoration(
                  color: Color.fromRGBO(255, 174, 0, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1, color: Color.fromRGBO(202, 172, 108, 1)),
                ),
                child: InkResponse(
                  borderRadius: new BorderRadius.all(new Radius.circular(10.0)),
                  //点击或者toch控件高亮时显示的控件在控件上层,水波纹下层
                  highlightColor: Colors.yellow,
                  //点击或者toch控件高亮的shape形状
                  highlightShape: BoxShape.rectangle,
                  //.InkResponse内部的radius这个需要注意的是，我们需要半径大于控件的宽，如果radius过小，显示的水波纹就是一个很小的圆，
                  //水波纹的半径
                  radius: 300.0,
                  //水波纹的颜色
                  splashColor: Colors.yellow,
                  //true表示要剪裁水波纹响应的界面   false不剪裁  如果控件是圆角不剪裁的话水波纹是矩形
                  containedInkWell: true,
                  //点击事件
                  onTap: () {
                    if (status == '0') {
                      res
                          .addOrder(obj['orderId'].toString(), userId)
                          .then((value) => {
                                if (value['code'] == '0')
                                  {
                                    showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new AlertDialog(
                                            title: new Text(
                                              '提示',
                                              style: new TextStyle(
                                                color: Colors.black54,
                                                fontSize: 18.0,
                                              ),
                                            ),
                                            content: new Text('操作成功！'),
                                            actions: <Widget>[
                                              FlatButton(
                                                  onPressed: () {
                                                    //更新视图.
                                                    setState(() {
                                                      alterPage('refresh');
                                                      this.isLoading = false;
                                                    });
                                                    Navigator.of(context).pop();
                                                  },
                                                  child: Text('确定'))
                                            ]);
                                      },
                                    )
                                  }
                                else
                                  {
                                    showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new AlertDialog(
                                            title: new Text(
                                              '提示',
                                              style: new TextStyle(
                                                color: Colors.black54,
                                                fontSize: 18.0,
                                              ),
                                            ),
                                            content: new Text(value['msg']),
                                            actions: <Widget>[
                                              FlatButton(
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                  child: Text('确定'))
                                            ]);
                                      },
                                    )
                                  }
                              });
                    } else {
                      res
                          .updateStatus((int.parse(status)).toString(),
                              obj['id'].toString(), obj['orderId'].toString())
                          .then((value) => {
                                if (value['code'] == '0')
                                  {
                                    showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new AlertDialog(
                                            title: new Text(
                                              '提示',
                                              style: new TextStyle(
                                                color: Colors.black54,
                                                fontSize: 18.0,
                                              ),
                                            ),
                                            content: new Text('操作成功！'),
                                            actions: <Widget>[
                                              FlatButton(
                                                  onPressed: () {
                                                    //更新视图.
                                                    setState(() {
                                                      alterPage('refresh');
                                                      this.isLoading = false;
                                                    });
                                                    Navigator.of(context).pop();
                                                  },
                                                  child: Text('确定'))
                                            ]);
                                      },
                                    )
                                  }
                                else
                                  {
                                    showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new AlertDialog(
                                            title: new Text(
                                              '提示',
                                              style: new TextStyle(
                                                color: Colors.black54,
                                                fontSize: 18.0,
                                              ),
                                            ),
                                            content: new Text(value['msg']),
                                            actions: <Widget>[
                                              FlatButton(
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                  child: Text('确定'))
                                            ]);
                                      },
                                    )
                                  }
                              });
                    }
                  },
                  child: Container(
                    //设置 child 居中
                    alignment: Alignment(0, 0),
                    height: 40,
                    child: Text(this.btnName,
                        style: TextStyle(
                            fontSize: 24, color: Color.fromRGBO(0, 0, 0, 1))),
                  ),
                ),
              )),
            ))
          ],
        ),
      ),
    );

//    if (this.status == '2') {
//      card = new SizedBox(
//  //    height: 550.0,  //设置高度
//        child: new Card(
//          elevation: 15.0,  //设置阴影
//          margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
//          shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),  //设置圆角
//          child: new Column(  // card只能有一个widget，但这个widget内容可以包含其他的widget
//            children: [
//              new ListTile(
//                  title: Row(
//                    children: <Widget>[
//                      new Container(
//                        child: Image.asset('images/time.png'),
//                        width: 20,
//                        height: 20,
//                      ),
//                      new Column(
//                       children: <Widget>[
//                        new Text('取餐时间：' + obj['createDateQ'],
//                        style: new TextStyle(color: Color.fromRGBO(255, 0, 42, 1), fontWeight: FontWeight.w100, fontSize: 13)),
//                        new Text('送达时间：' + obj['finishDate'],
//                        style: new TextStyle(color: Color.fromRGBO(255, 0, 42, 1), fontWeight: FontWeight.w100, fontSize: 13)),
//                       ],
//                      ),
//                    ],
//                  ),
//                  trailing: new Column(
//                    children: <Widget>[
//                      Text(obj['freight'].toString() + '元', style: TextStyle(color: Color.fromRGBO(255, 0, 42, 1), fontWeight: FontWeight.bold, fontSize: 16)),
//                      Text('已结算', style: TextStyle(color: Color.fromRGBO(255, 0, 42, 1), fontWeight: FontWeight.bold, fontSize: 16))
//                    ],
//                  ),
//              ),
//              new ListTile(
//                leading: Text('1.3KM  ', style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Color.fromRGBO(0, 0, 0, 1))),
//                title: Row(
//                  children: <Widget>[
//                    new Text(obj['shopName'].toString() + ' '+ obj['orderNo'].toString() + '号#已取货',style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Color.fromRGBO(0, 0, 0, 1))),
//                  ],
//                ),
//                subtitle: Text(obj['shopAddress'].toString()),
//              ),
//              new ListTile(
//                leading: Text('3.3KM  ', style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Color.fromRGBO(0, 0, 0, 1))),
//                title: new Text(obj['consignee'].toString() + ' 已送达',style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Color.fromRGBO(0, 0, 0, 1))),
//                subtitle: Text(obj['address'].toString()),
//              ),
//              new ListTile(
//                  title: Text('订单编号：' + obj['orderId'], style: TextStyle(fontSize: 13, fontWeight: FontWeight.w100),),
//              )
//            ],
//          ),
//        ),
//      );
//    }
    return card;
  }

  // 列表上拉刷新
  Future onRefresh() {
    return Future.delayed(Duration(seconds: 1), () {
      // 更新数据
      alterPage('refresh');
    });
  }

  // 列表下拉加载项
  Widget renderBottom() {
    if (this.isLoading) {
      if ((this.status == '0' && this.max < this.list.length) ||
          (this.status == '1' && this.max1 < this.list1.length) ||
          (this.status == '2' && this.max2 < this.list2.length)) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 15),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '努力加载中...',
                style: TextStyle(
                  fontSize: 15,
                  color: Color(0xFF333333),
                ),
              ),
              Padding(padding: EdgeInsets.only(left: 10)),
              SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 3),
              ),
            ],
          ),
        );
      } else {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 15),
          alignment: Alignment.center,
          child: Text(
            '已到达底线',
            style: TextStyle(
              fontSize: 15,
              color: Color(0xFF333333),
            ),
          ),
        );
      }
    } else {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: Text(
          '上拉加载更多',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      );
    }
  }

  // 下拉加载列表
  Future loadMoreData() {
    return Future.delayed(Duration(seconds: 1), () {
      setState(() {
        alterPage('');
      });
    });
  }

  @override
  void initState() {
    super.initState();
    this._getCounter();
//    Timer.periodic(new Duration(seconds: 3), (Timer timer){
//
//    });
//     this._initLocation();
    this.getLocation();

    this.controller = new TabController(
        vsync: this, // 动画效果的异步处理
        length: 3 // tab 个数
        );
    // tab页切换事件
    this.controller.addListener(() {
      if (this.controller.indexIsChanging) {
        //赋值 并更新数据
        this.setState(() {
          this.status = controller.index.toString();
          if (status == '0') {
            this.btnName = '抢单';
          } else if (status == '1') {
            this.btnName = '确认取货';
          } else if (status == '2') {
            this.btnName = '确认送达';
          }
//          else {
//            this.btnName = '';
//          }
          alterPage('refresh');
        });
      }
    });
    // 给列表滚动添加监听
    this.scrollController.addListener(() {
      // 滑动到底部的关键判断
      if (!this.isLoading &&
          this.scrollController.position.pixels >=
              this.scrollController.position.maxScrollExtent) {
        // 开始加载数据
        setState(() {
          this.isLoading = true;
          this.loadMoreData();
        });
      }
    });
  }

  // 当整个页面 dispose 时，记得把控制器也 dispose 掉，释放内存
  @override
  void dispose() {
    this.controller.dispose();
    this.scrollController.dispose();
    // this._amapLocation.stopLocate();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
            centerTitle: true,
            // 标题居中
            title: Text(
              '订单列表',
              style: TextStyle(
                color: Color.fromRGBO(255, 213, 140, 1),
              ),
            ),
            backgroundColor: Color.fromRGBO(30, 30, 30, 1),
            leading: IconButton(
                icon: Icon(
                  Icons.format_list_bulleted,
                  color: Color.fromRGBO(255, 213, 140, 1),
                ),
                onPressed: () {
                  print('菜单！！！！！！！！！！');
                }),
            actions: <Widget>[
              IconButton(
                  icon: Icon(Icons.message,
                      color: Color.fromRGBO(255, 213, 140, 1)),
                  onPressed: () {
                    print('消息！！！！！！！！！！');
                  })
            ],
            bottom: new TabBar(
              controller: this.controller,
              indicatorColor: Color.fromRGBO(255, 213, 140, 1),
              indicatorWeight: 4,
              indicatorSize: TabBarIndicatorSize.tab,
              unselectedLabelColor: Color.fromRGBO(255, 213, 140, 1),
              labelColor: Color.fromRGBO(255, 213, 140, 1),
              tabs: <Tab>[
                new Tab(text: '新任务'),
                new Tab(text: '待取货'),
                new Tab(text: '配送中'),
//                new Tab(text: '已完成'),
              ],
            )),
        body: new TabBarView(
          controller: this.controller, //配置控制器
          physics: new NeverScrollableScrollPhysics(), //禁止手势滑动
          children: [
            // Tab 内容
            RefreshIndicator(
              onRefresh: this.onRefresh,
              child: ListView.builder(
                controller: this.scrollController,
                itemCount: this.list.length + 1,
                // 有分割线
                itemBuilder: (context, item) {
                  if (item < this.list.length) {
                    return buildListData(context, this.list[item]);
                  } else {
                    return this.renderBottom();
                  }
                },
              ),
            ),
            RefreshIndicator(
              onRefresh: this.onRefresh,
              child: ListView.builder(
                controller: this.scrollController,
                itemCount: this.list1.length + 1,
                // 有分割线
                itemBuilder: (context, item) {
                  if (item < this.list1.length) {
                    return buildListData(context, this.list1[item]);
                  } else {
                    return this.renderBottom();
                  }
                },
              ),
            ),
            RefreshIndicator(
              onRefresh: this.onRefresh,
              child: ListView.builder(
                controller: this.scrollController,
                itemCount: this.list2.length + 1,
                // 有分割线
                itemBuilder: (context, item) {
                  if (item < this.list2.length) {
                    return buildListData(context, this.list2[item]);
                  } else {
                    return this.renderBottom();
                  }
                },
              ),
            ),
          ],
        ),
      ),
      onWillPop: () {
        print("返回键点击了");
        fil.writeCounter2('1');
        Navigator.pop(context);
      },
    );
  }
}
